package pbcrpt.service

import groovy.sql.Sql
import javax.annotation.Resource
import org.apache.commons.dbcp.BasicDataSource
import org.joda.time.DateTime
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import pub.platform.advance.utils.PropertyManager

/**
 * Created by IntelliJ IDEA.
 * User: zhanrui
 * Date: 11-9-29
 * To change this template use File | Settings | File Templates.
 */
@Service
@Scope("prototype")
class ExportService {
    @Resource
    protected BasicDataSource dataSource;

    public void generateReportFile(strdate10) {
        exportC01Y(strdate10)
        exportC01F(strdate10)
        exportC02Y(strdate10)
        exportC02F(strdate10)
    }

    def exportC01F(strdate10) {
        def localdb = new Sql(dataSource)
        def sql = "select * from pbc_rate_loandetl"
        exportDb2TxtFile(sql, "C01F", strdate10, localdb)
        localdb.close()
    }

    def exportC01Y(strdate10) {
        def localdb = new Sql(dataSource)
        def sql = "select * from pbc_rate_loanbal"
        exportDb2TxtFile(sql, "C01Y", strdate10, localdb)
        localdb.close()
    }

    def exportC02Y(strdate10) {
        def localdb = new Sql(dataSource)
        def sql = "select * from pbc_rate_depositbal"
        exportDb2TxtFile(sql, "C02Y", strdate10, localdb)
        localdb.close()
    }
    def exportC02F(strdate10) {
        def localdb = new Sql(dataSource)
        def sql = "select * from pbc_rate_depositdetl"
        exportDb2TxtFile(sql, "C02F", strdate10, localdb)
        localdb.close()
    }



    def exportDb2TxtFile(sql, prefix, strdate10, localdb) {
        def count = 0

        def org_code = PropertyManager.getProperty("ORG_CODE")
        def reportPath = PropertyManager.getProperty("ROOTPATH") + 'pbc/'

        DateTime dateTime = new DateTime(strdate10);
        def yyyymm = dateTime.toString("yyyyMM");
        def filename = reportPath + prefix + org_code + yyyymm + ".txt";

        new File(filename).withPrintWriter {printWriter ->
            localdb.rows(sql).each {Map row ->
                def buffer = row.collect {k, v -> v == null ? '' : "$v"}.join(';')
                printWriter.println buffer
                count++
                if (count % 1000 == 0) {
                    println count
                }
            }
        }
    }

    public void generateZipFile(yyyymm) {
        Process p = "cmd /c dir".execute()
        println "${p.text}"
    }

}
